import {getInfo, login, logout} from "@/api/login";
import {defineStore} from "pinia";
import {getToken, removeToken, setExpiresIn, setStore, setToken,} from "@/utils/auth";
import {store} from "@/store";
import {useTagsViewStore} from "@/store/modules/tagsView";

export const useUserStore = defineStore("user", () => {
    const user = {
        token: getToken(),
        name: "",
        avatar: "",
        roles: [],
        permissions: [],
        configPersonList: [],
        userInfo: {} as UserInfoBusi,
        sysRoleGroup: [] as any,
        deptList: [],
        expires_in: "",
        currentSelectDept: "",
        // 当前科室名称
        currentSelectDeptName: ""
    };

    function Login(userInfo: any) {
        const username = userInfo.username.trim();
        const password = userInfo.password;
        const code = userInfo.code;
        const uuid = userInfo.uuid;
        return new Promise((resolve, reject) => {
            login(username, password, code, uuid)
                .then((res) => {
                    let data = res.data;
                    setToken(data.access_token);
                    setTokenUser(data.access_token);
                    setExpiresIn(data.expires_in);
                    setExpiresInUser(data.expires_in);
                    resolve(null);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    // 获取用户信息
    function GetInfo() {
        return new Promise((resolve, reject) => {
            getInfo()
                .then((res) => {
                    const userInfo = res.data.user;
                    // 用户头像、系统右上角头像
                    if (res.data.roles && res.data.roles.length > 0) {
                        // 验证返回的roles是否是一个非空数组
                        setRolesUser(res.data.roles);
                        setPermissionsUser(res.data.permissions);
                    } else {
                        setRolesUser(["ROLE_DEFAULT"]);
                    }
                    setSysrolegroupUser(userInfo.sysRoleGroupList);
                    setDeptlistUser(res.data.deptList);
                    setNameUser(userInfo.userName);
                    setAvatarUser(userInfo.avatar);
                    setConfigPersonList(res.data.configPersonList);
                    setUserinfoUser(userInfo);
                    resolve(res);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    function setTokenUser(token) {
        user.token = token;
    }

    function setExpiresInUser(time) {
        user.expires_in = time;
    }

    function setRolesUser(roles) {
        user.roles = roles;
    }

    function setPermissionsUser(permissions) {
        user.permissions = permissions;
    }

    function setConfigPersonList(configPersonList) {
        user.configPersonList = configPersonList;
    }

    function setSysrolegroupUser(sysRoleGroup) {
        user.sysRoleGroup = sysRoleGroup;
    }

    function setDeptlistUser(deptList) {
        user.deptList = deptList;
    }

    function setNameUser(name) {
        user.name = name;
    }

    function setAvatarUser(avatar) {
        user.avatar = avatar;
    }

    function setUserinfoUser(userInfo) {
        user.userInfo = userInfo;
    }

    /**
     * 设置当前选择科室
     * @param currentSelectDept
     */
    function setCurrentSelectDept(currentSelectDept:string, currentSelectDeptName:string) {
        user.currentSelectDept = currentSelectDept;
        // 当前科室名称
        user.currentSelectDeptName = currentSelectDeptName;
        user.userInfo.loginDeptId = currentSelectDept
        console.log('Pinia 状态更新:', user.currentSelectDept, '--------------',user.currentSelectDeptName);

    }

    // 退出系统
    function LogOut() {
        const useTagsView = useTagsViewStore();
        return new Promise((resolve, reject) => {
            logout()
                .then(() => {
                    setTokenUser("");
                    setRolesUser([]);
                    setPermissionsUser([]);
                    setServiceCheckInfo("");
                    useTagsView.delAllViews();
                    removeToken();
                    resolve(resolve(null));
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    // 将选中的服务id存入  window.sessionStorage
    function setServiceCheckInfo(roleGroupId) {
        setStore({
            //@ts-ignore
            name: "roleGroupId" + "-" + user.userInfo.userId,
            content: roleGroupId,
            type: true,
        });
    }

    // 前端 登出
    function FedLogOut() {
        return new Promise((resolve) => {
            setTokenUser("");
            removeToken();
            resolve(resolve(null));
        });
    }

    return {
        Login,
        GetInfo,
        FedLogOut,
        setServiceCheckInfo,
        LogOut,
        user,
        setCurrentSelectDept,
        setConfigPersonList,
    };
});

export function useUserStoreHook() {
    return useUserStore(store);
}
